import { AutoComplete, Card, Col, Empty, Input, Row, Tooltip, Tree } from 'antd';
import React, { useMemo, useContext } from 'react';
import type { TreeProps } from 'antd/es/tree';
import { SearchOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import InfiniteScroll from 'react-infinite-scroller';
import { loopArray, tooltipLength } from '@/utils';
import { CheckOutlined } from '@ant-design/icons';
import { ToAssetControllerAPI } from '../common/type';
import MyIcon from '@/components/MyIcon';
import { ToAssetControllerContext } from '../mconfig';
/**
 * @UpdatePlanListCard 材料弹窗左侧计划列表组件
 * @param onSelect 选中事件
 * @param dataSource 数据源
 * @returns
 */
export const UpdatePlanListCard: React.FC<ToAssetControllerAPI.IUpdatePlanListCardProps> = ({
  onSelect,
  dataSource,
  onChange,
  PlanIdsMemo,
  loading,
  getPlanSev,
}) => {
  /** 上下文 */
  const { prefixCls } = useContext(ToAssetControllerContext);

  /** 解构state和方法 */
  const { selectKeys, setSelectKeys, typeTreeSearchObj, setTypeTreeSearchObj, searchLeftList } = onChange;

  /** 点击item获取对象 */
  const onChangeSelect = (selectedKeys: Record<string, any>) => {
    if (selectedKeys?.length) {
      setSelectKeys(selectedKeys);
      onSelect(selectedKeys?.toString());
    } else {
      onSelect(null);
      setSelectKeys(selectedKeys);
    }
  };

  /** 搜索框的事件 */
  const onInputChange = (ev: Record<string, any>) => {
    searchLeftList({ title: ev?.target?.value });
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      searchValue: ev?.target?.value,
    });
  };

  /** 自动完成组件options */
  const autoCompleteOptions = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        const name = item?.applyTitle;
        if (name?.includes(typeTreeSearchObj?.searchValue)) {
          const nameLength = name?.length;
          const select = name?.search(typeTreeSearchObj?.searchValue);
          const searchLength = typeTreeSearchObj?.searchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = typeTreeSearchObj?.searchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.id,
            label: (
              // <Tooltip title={selectStr ? tooltipLength(selectStr, 20) : undefined}>
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
              // </Tooltip>
            ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(dataSource);
    return option;
  }, [dataSource, typeTreeSearchObj?.searchValue]);

  /** 自动完成组件的事件 */
  const onAutoSelectLeft = (value: string, option: any) => {
    const optionId = option?.key;
    const targetNode = loopArray(dataSource)?.find((i) => i?.id == optionId);

    const searchObj: Record<string, any> = {
      searchValue: value,
      // autoExpandParent: true,
      expandedKeys: [targetNode?.pID],
    };

    setTypeTreeSearchObj(searchObj);
    setSelectKeys([optionId]);

    // 向外抛出
    // setSelectKeys(optionId)
    onSelect(optionId);
  };

  /** 树展开方法 */
  const onTreeExpand = (e: any) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      expandedKeys: e,
      // autoExpandParent: false
    });
  };

  /** Tree组件的check方法 */
  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {};

  /** 处理树数据 */
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.applyTitle;
      const nameLength = name?.length;
      const select = name?.search(typeTreeSearchObj?.searchValue);
      const searchLength = typeTreeSearchObj?.searchValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = typeTreeSearchObj?.searchValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <Row style={{ width: '100%' }}>
            <Col span={17}>
              <span className={pageStyles['over-flow-hidden']} style={{ fontWeight: 600 }}>
                <span className={pageStyles['over-flow-hidden']}>
                  {afterStr}
                  <span style={{ color: '#f50' }}>{selectStr}</span>
                  {beforeStr}
                </span>
              </span>
            </Col>
            <Col span={6}>
              <span style={{ fontWeight: 600 }}>{item?.createTime?.split(' ')?.[0] || '--'}</span>
            </Col>
            <Col span={24}>{/* <div style={{ fontSize: 16, color: '#7b7b7b' }}>创建人：{item?.createrName || '--'}</div> */}</Col>
            <Col span={24}>
              <div style={{ fontSize: 16, color: '#7b7b7b', marginTop: '15px' }}>创建部门：{item?.createDepartmentName || '--'}</div>
            </Col>
          </Row>
        ) : (
          <Row style={{ width: '100%' }}>
            <Col span={17}>
              <span className={pageStyles['over-flow-hidden']} style={{ fontWeight: 600 }}>
                {item?.applyTitle}
              </span>
            </Col>
            <Col span={30}>
              <span style={{ fontWeight: 600 }}>{item?.createTime?.split(' ')?.[0] || '--'}</span>
            </Col>
            <Col span={24}>{/* <div style={{ fontSize: 16, color: '#7b7b7b' }}>创建人：{item?.createrName || '--'}</div> */}</Col>
            <Col span={24}>
              <div style={{ fontSize: 16, color: '#7b7b7b', marginTop: '15px' }}>创建部门：{item?.createDepartmentName || '--'}</div>
            </Col>
          </Row>
        );
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              margin: '5px 0',
              padding: '5px',
              borderRadius: 7,
              background: '#f5f4f4',
              position: 'relative',
            }}
            id={item?.id}
          >
            <Tooltip title={item?.applyTitle ? tooltipLength(item?.applyTitle, 25) : undefined}>{titleTree}</Tooltip>
            {PlanIdsMemo?.find((ite) => ite == item?.id) ? (
              <a style={{ paddingLeft: 10, position: 'absolute', right: '0', bottom: '0' }}>
                {/* <span style={{fontSize:"50px"}} className='iconfont icon-xuanzejiaobiao' ></span>  */}
                <MyIcon type="icon-xuanzejiaobiao" style={{ fontSize: '50px' }} />
              </a>
            ) : null}
          </div>
        ),
        searchTitle: item?.applyTitle,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  return (
    <Card
      className={`${prefixCls}-plan-list`}
      title={
        <>
          <AutoComplete
            style={{ width: '100%' }}
            options={autoCompleteOptions}
            notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            onSelect={onAutoSelectLeft}
          >
            <Input placeholder="请按名称搜索" suffix={<SearchOutlined />} onChange={onInputChange} value={typeTreeSearchObj?.searchValue || ''} />
          </AutoComplete>
        </>
      }
      bodyStyle={{ padding: '0px' }}
    >
      <div className={pageStyles['InfiniteScrollView']}>
        <InfiniteScroll
          pageStart={1}
          className="InfiniteScrollDiv"
          useWindow={false}
          initialLoad={false}
          loadMore={getPlanSev}
          hasMore={!loading}
          style={{ padding: 3 }}
        >
          {dataSource?.length === 0 ? (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          ) : (
            <Tree
              className={`${prefixCls}-plan-list-TreeCpt`}
              onSelect={(item: Record<string, any>) => onChangeSelect(item)}
              blockNode={true}
              onCheck={onCheck}
              treeData={orgTreeData(dataSource || [])}
              selectedKeys={selectKeys}
              expandedKeys={typeTreeSearchObj?.expandedKeys}
              defaultExpandParent={true}
              checkable={false}
              onExpand={onTreeExpand}
            />
          )}
        </InfiniteScroll>
      </div>
    </Card>
  );
};
